﻿using LightWadf.Core.Util;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading.Tasks;

namespace LightWadf.Core.Handler
{
    public class HandlerDispatcher
    {
        private IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());

        public HandlerDispatcher(RequestDelegate next)
        {

        }

        public async Task Invoke(HttpContext context)
        {
            ICustomHttpHandler handler = null;
            string key = context.Request.Cookies["lwend"];
            if (!string.IsNullOrEmpty(key))
            {
                handler = this.cache.Get<ICustomHttpHandler>(key);
            }
            if(handler == null)
            {
                key = Guid.NewGuid().ToString();
                context.Response.Cookies.Append("lwend", key);
                handler = new DefaultHandler();
                MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
                // 如果数分钟内该会话没有再次发起请求，则释放 Handler
                options.SlidingExpiration = Utility.GlobalConfiguration.HandlerSlidingExpiration;
                this.cache.Set(key, handler, options);
            }
            
            if(handler != null)
            {
                await handler.ProcessRequest(context);
            }
        }
    }

    public static class HandlerMiddlewareExtension
    {
        public static IApplicationBuilder UseHandlerMiddleware(this IApplicationBuilder builder, IHostingEnvironment envi)
        {
            Utility.HostingEnvironment = envi;
            return builder.UseMiddleware<HandlerDispatcher>();
        }
    }
}
